package bootstrap

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"wskyygyso/api/app/http/middlewares"
	"wskyygyso/api/routes"
)

//SetUpRoute 注册路由
func SetUpRoute(r *gin.Engine) {
	registerGlobalMiddleWare(r)
	routes.RegisterApiRoutes(r)
	setUp404handler(r)
}

//registerGlobalMiddleWare 注册全局中间件
func registerGlobalMiddleWare(r *gin.Engine) {
	//先进后出
	//第一个是日志 前置获取初始请求信息  后置记录返回信息
	//第二个是recovery defer 获取执行过程中的panic等信息 记录进日志
	r.Use(
		middlewares.Logger(),
		middlewares.Recovery(),
		middlewares.ForceUa(),
	)
}

//setUp404handler 未找到路由时的处理方法
func setUp404handler(r *gin.Engine) {
	r.NoRoute(func(context *gin.Context) {
		acceptString := context.Request.Header.Get("Accept")
		if strings.Contains(acceptString, "text/html") {
			context.String(http.StatusOK, "404 not found")
		} else {
			context.JSON(http.StatusOK, gin.H{
				"error":         404,
				"error_message": "路由未定义，请确认 url 和请求方法是否正确。",
			})
		}
	})
}
